package com.chris.libs.base.x.mvpp.mvpp;

import android.app.Activity;
import android.content.Context;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.chris.libs.base.x.mvpp.activity.BaseActivity;
import com.chris.libs.base.x.mvpp.application.AppGlobal;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author Chris chan
 * Create on： 2025/2/1 10:15
 * Use for:
 * Explain:
 */
public abstract class AbsStandardActivityViewProxy extends AbsViewProxy
        implements ViewProxyAssist, LifecycleObserver {
    protected BaseActivity activity;
    protected Unbinder unbinder;

    public AbsStandardActivityViewProxy() {
    }

    public AbsStandardActivityViewProxy(@NonNull Context context, @NonNull View contentView, @NonNull LifecycleOwner lifecycleOwner) {
        super(context, contentView, lifecycleOwner);
    }

    public AbsStandardActivityViewProxy(@NonNull BaseActivity activity) {
        super(activity, activity.getContentView(), activity);
        this.activity = activity;
        this.unbinder = ButterKnife.bind(this, this.contentView);
        init();
        initView();
        setupEvent();
        onReady();
    }

    /**
     * 本方法只适用于使用默认构造函数创建对象后赋值
     *
     * @param activity
     */
    public void bind(BaseActivity activity) {
        this.context = activity;
        this.contentView = activity.getContentView();
        this.lifecycleOwner = activity;
        this.activity = activity;
        this.unbinder = ButterKnife.bind(this, this.contentView);
        init();
        initView();
        setupEvent();
        onReady();
    }

    protected abstract void init();

    protected abstract void initView();

    protected abstract void setupEvent();

    protected abstract void onReady();

    protected <VM extends ViewModel> VM getViewModel(Class<VM> viewModelClass) {
        return new ViewModelProvider(this.activity).get(viewModelClass);
    }

    protected <VM extends ViewModel> VM getGlobalViewModel(Class<VM> viewModelClass) {
        return new ViewModelProvider(AppGlobal.getOwner()).get(viewModelClass);
    }

    @Override
    public Context requireContext() {
        return this.context;
    }

    @Override
    public Activity requireActivity() {
        return this.activity;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        if (null != this.unbinder) {
            this.unbinder.unbind();
        }
    }
}
